#pragma once
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <fstream>
#include <mutex>
#include "util.hpp"

namespace yjz_index
{
    struct DocInfo
    {
        std::string title;
        std::string content;
        std::string url;
        uint64_t doc_id;
    };

    struct InvertedElem
    {
        uint64_t doc_id;     // 文档ID
        std::string word;    // 关键字
        int weight;          // 权重
    };

    class Index
    {
    private:
        Index(){}
        Index(const Index&) = delete;
        Index& operator=(const Index&) = delete;

        static Index *_instance;
        static std::mutex _mutex;
    public:
        using InvertedList = std::vector<InvertedElem>;
        ~Index(){}

        static Index* GetInstance()
        {
            if (_instance == nullptr)
            {
                std::unique_lock<std::mutex> lock(_mutex);
                if (_instance == nullptr)
                {
                    _instance = new Index();
                }
            }
            return _instance;
        }

        // 根据文档ID找到文档内容
        DocInfo* GetForwardIndex(uint64_t doc_id)
        {
            if (doc_id >= _forward_index.size())
            {
                std::cerr << "doc_id out range!" << std::endl;
                return nullptr;
            }
            return &_forward_index[doc_id];
        }

        // 根据关键字找到倒排拉链
        InvertedList* GetInvertedList(const std::string &word)
        {
            auto it = _inverted_index.find(word);
            if (it == _inverted_index.end())
            {
                std::cerr << word << " not exists!" << std::endl;
                return nullptr;
            }
            return &it->second;
        }

        // 根据格式化后的文档，构建正排、倒排索引
        bool BuildIndex(const std::string &input)
        {
            std::ifstream in(input, std::ios::in | std::ios::binary);
            if (in.is_open() == false)
            {
                std::cerr << input << " open fail!" << std::endl;
                return false;
            }
            std::string line;
            while (std::getline(in, line))
            {
                DocInfo *doc = BuildForwardIndex(line);
                if (doc == nullptr)
                {
                    std::cerr << "build " << line << " fail!" << std::endl;
                    continue;
                }
                BuildInvertedIndex(*doc);
            }
            return true;
        }
    private:
        // 构建正排索引
        DocInfo* BuildForwardIndex(const std::string &line)
        {
            // 解析line，字符串切分
            std::vector<std::string> results;
            const std::string sep = "\3";
            yjz_util::StringUtil::Split(line, &results, sep);
            if (results.size() != 3)
            {
                return nullptr;
            }
            // 将切分好的字符串构建DocInfo
            DocInfo doc;
            doc.title = results[0];
            doc.content = results[1];
            doc.url = results[2];
            doc.doc_id = _forward_index.size(); // 先更新文档ID再插入
            _forward_index.push_back(std::move(doc));
            return &_forward_index.back();
        }

        // 构建倒排索引
        bool BuildInvertedIndex(const DocInfo &doc)
        {
            // doc -> 倒排拉链
            struct word_cnt
            {
                int title_cnt;
                int content_cnt;
                word_cnt() : title_cnt(0), content_cnt(0) {}
            }; 

            std::unordered_map<std::string, word_cnt> word_map; // 暂存词频
            std::vector<std::string> title_words;
            yjz_util::JiebaUtil::CutString(doc.title, &title_words);
            for (auto &s : title_words)
            {
                boost::to_lower(s); // 全部转化为小写
                word_map[s].title_cnt++;
            }
            std::vector<std::string> content_words;
            yjz_util::JiebaUtil::CutString(doc.content, &content_words);
            for (auto &s : content_words)
            {
                boost::to_lower(s); 
                word_map[s].content_cnt++;
            }

            for (auto &word_pair : word_map)
            {
                InvertedElem item;
                item.doc_id = doc.doc_id;
                item.word = word_pair.first;
                item.weight = 10 * word_pair.second.title_cnt + word_pair.second.content_cnt;
                InvertedList &inverted_list = _inverted_index[word_pair.first];
                inverted_list.push_back(std::move(item));
            }
            return true;
        }
    private:
        // 将数组下标作为文档ID
        std::vector<DocInfo> _forward_index;  // 正排索引
        std::unordered_map<std::string, InvertedList> _inverted_index;
    };
    Index* Index::_instance= nullptr;
    std::mutex Index::_mutex;
}